package com.xiaoyi.pdocrlibrary;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.Point;
import com.xiaoyi.pdocrlibrary.OCRPredictorNative;
import java.io.File;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Vector;

public class Predictor {
    private static final String TAG = "Predictor";
    public String cpuPowerMode = "LITE_POWER_HIGH";
    public int cpuThreadNum = 4;
    public int inferIterNum = 1;
    protected float inferenceTime = 0.0f;
    protected String inputColorFormat = "BGR";
    protected Bitmap inputImage = null;
    protected float[] inputMean = {0.485f, 0.456f, 0.406f};
    protected long[] inputShape = {1, 3, 960};
    protected float[] inputStd = {4.366812f, 4.4642854f, 4.4444447f};
    public boolean isLoaded = false;
    private List<OCRResultBean> mOcrResultModelList;
    public String modelName = "";
    public String modelPath = "";
    protected Bitmap outputImage = null;
    protected volatile String outputResult = "";
    protected OCRPredictorNative paddlePredictor = null;
    protected float postprocessTime = 0.0f;
    protected float preprocessTime = 0.0f;
    protected float scoreThreshold = 0.1f;
    public int warmupIterNum = 1;
    protected Vector<String> wordLabels = new Vector<>();

    public boolean init(Context context, String str, String str2) {
        boolean loadModel = loadModel(context, str, this.cpuThreadNum, this.cpuPowerMode);
        this.isLoaded = loadModel;
        if (!loadModel) {
            return false;
        }
        boolean loadLabel = loadLabel(context, str2);
        this.isLoaded = loadLabel;
        return loadLabel;
    }

    public boolean init(Context context, String str, String str2, int i, String str3, String str4, long[] jArr, float[] fArr, float[] fArr2, float f) {
        if (jArr.length != 3 || ((long) fArr.length) != jArr[1] || ((long) fArr2.length) != jArr[1] || jArr[0] != 1) {
            return false;
        }
        if ((jArr[1] != 1 && jArr[1] != 3) || !str4.equalsIgnoreCase("BGR") || !init(context, str, str2)) {
            return false;
        }
        this.inputColorFormat = str4;
        this.inputShape = jArr;
        this.inputMean = fArr;
        this.inputStd = fArr2;
        this.scoreThreshold = f;
        return true;
    }

    /* access modifiers changed from: protected */
    public boolean loadModel(Context context, String str, int i, String str2) {
        releaseModel();
        if (str.isEmpty()) {
            return false;
        }
        if (!str.substring(0, 1).equals("/")) {
            String str3 = context.getCacheDir() + "/" + str;
            PaddleUtils.copyDirectoryFromAssets(context, str, str3);
            str = str3;
        }
        if (str.isEmpty()) {
            return false;
        }
        OCRPredictorNative.Config config = new OCRPredictorNative.Config();
        config.cpuThreadNum = i;
        config.detModelFilename = str + File.separator + "ch_ppocr_mobile_v2.0_det_opt.nb";
        config.recModelFilename = str + File.separator + "ch_ppocr_mobile_v2.0_rec_opt.nb";
        config.clsModelFilename = str + File.separator + "ch_ppocr_mobile_v2.0_cls_opt.nb";
        config.cpuPower = str2;
        this.paddlePredictor = new OCRPredictorNative(context, config);
        this.cpuThreadNum = i;
        this.cpuPowerMode = str2;
        this.modelPath = str;
        this.modelName = str.substring(str.lastIndexOf("/") + 1);
        return true;
    }

    public void releaseModel() {
        OCRPredictorNative oCRPredictorNative = this.paddlePredictor;
        if (oCRPredictorNative != null) {
            oCRPredictorNative.destory();
            this.paddlePredictor = null;
        }
        this.isLoaded = false;
        this.cpuThreadNum = 1;
        this.cpuPowerMode = "LITE_POWER_HIGH";
        this.modelPath = "";
        this.modelName = "";
    }

    /* access modifiers changed from: protected */
    public boolean loadLabel(Context context, String str) {
        this.wordLabels.clear();
        this.wordLabels.add("black");
        try {
            InputStream open = context.getAssets().open(str);
            byte[] bArr = new byte[open.available()];
            open.read(bArr);
            open.close();
            for (String str2 : new String(bArr).split("\n")) {
                this.wordLabels.add(str2);
            }
            return true;
        } catch (Exception unused) {
            return false;
        }
    }

    public boolean runModel() {
        int[] iArr;
        if (this.inputImage != null && isLoaded()) {
            Bitmap resizeWithStep = PaddleUtils.resizeWithStep(this.inputImage, Long.valueOf(this.inputShape[2]).intValue(), 32);
            Date date = new Date();
            char c = 1;
            int i = (int) this.inputShape[1];
            int width = resizeWithStep.getWidth();
            int height = resizeWithStep.getHeight();
            float[] fArr = new float[(i * width * height)];
            float f = 255.0f;
            int i2 = 3;
            if (i == 3) {
                if (this.inputColorFormat.equalsIgnoreCase("RGB")) {
                    iArr = new int[]{0, 1, 2};
                } else if (!this.inputColorFormat.equalsIgnoreCase("BGR")) {
                    return false;
                } else {
                    iArr = new int[]{2, 1, 0};
                }
                int i3 = width * height;
                int[] iArr2 = {i3, i3 * 2};
                resizeWithStep.getPixel(resizeWithStep.getWidth() - 1, resizeWithStep.getHeight() - 1);
                int i4 = 0;
                while (i4 < height) {
                    int i5 = 0;
                    while (i5 < width) {
                        int pixel = resizeWithStep.getPixel(i5, i4);
                        float[] fArr2 = new float[i2];
                        fArr2[0] = ((float) Color.red(pixel)) / f;
                        fArr2[c] = ((float) Color.green(pixel)) / f;
                        fArr2[2] = ((float) Color.blue(pixel)) / f;
                        int i6 = (i4 * width) + i5;
                        float f2 = fArr2[iArr[0]];
                        float[] fArr3 = this.inputMean;
                        float[] fArr4 = this.inputStd;
                        fArr[i6] = (f2 - fArr3[0]) / fArr4[0];
                        fArr[i6 + iArr2[0]] = (fArr2[iArr[1]] - fArr3[1]) / fArr4[1];
                        fArr[i6 + iArr2[1]] = (fArr2[iArr[2]] - fArr3[2]) / fArr4[2];
                        i5++;
                        c = 1;
                        f = 255.0f;
                        i2 = 3;
                    }
                    i4++;
                    c = 1;
                    f = 255.0f;
                    i2 = 3;
                }
            } else if (i == 1) {
                for (int i7 = 0; i7 < height; i7++) {
                    for (int i8 = 0; i8 < width; i8++) {
                        int pixel2 = this.inputImage.getPixel(i8, i7);
                        fArr[(i7 * width) + i8] = (((((float) ((Color.red(pixel2) + Color.green(pixel2)) + Color.blue(pixel2))) / 3.0f) / 255.0f) - this.inputMean[0]) / this.inputStd[0];
                    }
                }
            }
            this.preprocessTime = (float) (new Date().getTime() - date.getTime());
            for (int i9 = 0; i9 < this.warmupIterNum; i9++) {
                this.paddlePredictor.runImage(fArr, width, height, i, this.inputImage);
            }
            this.warmupIterNum = 0;
            Date date2 = new Date();
            ArrayList<OcrResultModel> runImage = this.paddlePredictor.runImage(fArr, width, height, i, this.inputImage);
            this.inferenceTime = ((float) (new Date().getTime() - date2.getTime())) / ((float) this.inferIterNum);
            drawResults(postprocess(runImage));
            return true;
        }
        return false;
    }

    public boolean isLoaded() {
        return this.paddlePredictor != null && this.isLoaded;
    }

    public String modelPath() {
        return this.modelPath;
    }

    public String modelName() {
        return this.modelName;
    }

    public int cpuThreadNum() {
        return this.cpuThreadNum;
    }

    public String cpuPowerMode() {
        return this.cpuPowerMode;
    }

    public float inferenceTime() {
        return this.inferenceTime;
    }

    public Bitmap inputImage() {
        return this.inputImage;
    }

    public Bitmap outputImage() {
        return this.outputImage;
    }

    public String outputResultToString() {
        return this.outputResult;
    }

    public List<OCRResultBean> outputResultList() {
        return this.mOcrResultModelList;
    }

    public float preprocessTime() {
        return this.preprocessTime;
    }

    public float postprocessTime() {
        return this.postprocessTime;
    }

    public void setInputImage(Bitmap bitmap) {
        if (bitmap != null) {
            this.inputImage = bitmap.copy(Bitmap.Config.ARGB_8888, true);
        }
    }

    private ArrayList<OcrResultModel> postprocess(ArrayList<OcrResultModel> arrayList) {
        Iterator<OcrResultModel> it = arrayList.iterator();
        while (it.hasNext()) {
            OcrResultModel next = it.next();
            StringBuffer stringBuffer = new StringBuffer();
            for (Integer num : next.getWordIndex()) {
                int intValue = num.intValue();
                if (intValue < 0 || intValue >= this.wordLabels.size()) {
                    stringBuffer.append("×");
                } else {
                    stringBuffer.append(this.wordLabels.get(intValue));
                }
            }
            next.setLabel(stringBuffer.toString());
        }
        return arrayList;
    }

    private void drawResults(ArrayList<OcrResultModel> arrayList) {
        this.mOcrResultModelList = new ArrayList();
        StringBuffer stringBuffer = new StringBuffer("");
        for (int i = 0; i < arrayList.size(); i++) {
            OcrResultModel ocrResultModel = arrayList.get(i);
            try {
                List<Point> points = ocrResultModel.getPoints();
                this.mOcrResultModelList.add(new OCRResultBean(ocrResultModel.getLabel(), ocrResultModel.getConfidence(), points.get(0).x + ((points.get(2).x - points.get(0).x) / 2), points.get(0).y + ((points.get(2).y - points.get(0).y) / 2), points));
            } catch (Exception e) {
                e.printStackTrace();
            }
            stringBuffer.append(ocrResultModel.getLabel());
            stringBuffer.append("\n");
        }
        this.outputResult = stringBuffer.toString();
        this.outputImage = this.inputImage;
        Canvas canvas = new Canvas(this.outputImage);
        Paint paint = new Paint();
        paint.setStyle(Paint.Style.FILL);
        paint.setColor(Color.parseColor("#3B85F5"));
        paint.setAlpha(50);
        Paint paint2 = new Paint();
        paint2.setColor(Color.parseColor("#3B85F5"));
        paint2.setStrokeWidth(5.0f);
        paint2.setStyle(Paint.Style.STROKE);
        Iterator<OcrResultModel> it = arrayList.iterator();
        while (it.hasNext()) {
            Path path = new Path();
            List<Point> points2 = it.next().getPoints();
            path.moveTo((float) points2.get(0).x, (float) points2.get(0).y);
            for (int size = points2.size() - 1; size >= 0; size--) {
                Point point = points2.get(size);
                path.lineTo((float) point.x, (float) point.y);
            }
            canvas.drawPath(path, paint2);
            canvas.drawPath(path, paint);
        }
    }
}
